import { dataApi, addApi, editApi, findByIdApi, deleteByIdApi } from '@/api/dicttype'

import { valid } from 'mockjs'
// import { getDeptTree } from '@/api/dept';
import { Message } from 'element-ui'
const mixin = {
  data() {
    function validateUserName/* 用户名验证*/(rule, value, callback) {
      const Regex = /^[a-zA-Z0-9_-]{4,18}$/
      if (Regex.test(value)) { // 使用正则表达式校验用户输入的值，校验成功返回true，否则返回false
        callback() // 放行，说明value值通过了校验
      } else {
        callback(new Error('用户名包含字母、数字、下划线、减号'))
      }
    }
    function validateEmail/* 邮箱验证*/(rule, value, callback) {
      const Regex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/
      // js中，value值为'', undefined, 0, null, 等价于false
      if (value) {
        if (!Regex.test(value)) {
          callback(new Error('邮箱不合法'))
          return
        }
      }
      callback()
    }
    function validatePhone/* 电话号码验证*/(role, value, callback) {
      const Regex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (value) {
        if (!Regex.test(value)) {
          callback(new Error('手机号码不合法'))
          return
        }
      }
      callback()
    }
    function validatePasword/* 密码验证*/(role, value, callback) {
      const Regex = /(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}/
      if (value) {
        if (!Regex.test(value)) {
          callback(new Error('必须包含字母、数字、特称字符，至少8个字符'))
          return
        }
      }
      callback()
    }
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false, /* 弹出对话框*/
      primaryKey: 'id',/*主键属性*/
      dataApi: dataApi, /* 查询函数*/
      addApi: addApi, /* 新增函数*/
      editApi: editApi, /* 编辑函数*/
      findByIdApi: findByIdApi, /* 根据主键查找函数*/
      deleteByIdApi: deleteByIdApi, /* 删除函数*/
      list: [],
      deptTree: [],
      itemBatchData: [], /* 多选处理*/
      infoBoxType: 'info', /* 记录确认消息弹出的类型*/
      infoType: 'info', /* 记录顶部普通的类型*/
      formInline:{
          id:undefined, /*字典主键*/
          dictName:undefined, /*字典名称*/
          dictType:undefined, /*字典类型*/
          status:undefined, /*状态*/
          createBy:undefined, /*创建者*/
          createTime:undefined, /*创建时间*/
          updateBy:undefined, /*更新者*/
          updateTime:undefined, /*更新时间*/
          remark:undefined, /*备注*/
      },
      treeData: [{
        label: '一级 1',
        children: [{
          label: '二级 1-1',
          children: [{ label: '三级 1-1-1' }]
        }]
      }, {
        label: '一级 2',
        children: [{
          label: '二级 2-1',
          children: [{ label: '三级 2-1-1' }]
        }, {
          label: '二级 2-2',
          children: [{ label: '三级 2-2-1' }]
        }]
      }, {
        label: '一级 3',
        children: [{
          label: '二级 3-1',
          children: [{ label: '三级 3-1-1' }]
        }, {
          label: '二级 3-2',
          children: [{ label: '三级 3-2-1' }]
        }]
      }],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultStates: ['所有', '正常', '停用'],
      fromView: {
        type: 1, /* 请求类型-新增/修改/删除/批量删除*/
          id:undefined, /*字典主键*/
          dictName:undefined, /*字典名称*/
          dictType:undefined, /*字典类型*/
          status:undefined, /*状态*/
          createBy:undefined, /*创建者*/
          createTime:undefined, /*创建时间*/
          updateBy:undefined, /*更新者*/
          updateTime:undefined, /*更新时间*/
          remark:undefined, /*备注*/

        isFormLoadding: false/*加载等待...*/
      },
      formRules: {
        userName: [
          { required: true, message: '请输入用户账号', trigger: 'blur' },
          { min: 4, max: 18, message: '用户账号4-18位', trigger: 'blur' },
          { validator: validateUserName, trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        phonenumber: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        pasword: [
          { validator: validatePasword, trigger: 'blur' }
        ]

      },
      buttonText: {
        editSubmit: '立即创建'
      }
    }
  },

  // vue中的生命周期钩子函数
  // 当前页面本质上就是一个Vue的对象
  // 在这个Vue对象被实例化后，执行created钩子函数
  created() {
    // 发起异步请求，向后端请求数据
    // axios会将结果封装到Promise对象中
    this.fetchList()
    /* 查询获取树结构*/
    // getDeptTree().then(resp => {
    //   // 获取服务器返回的数据
    //   this.deptTree = resp.data
    //   console.log("钩子函数",resp.data)
    // })
    console.groupEnd()
  },
  methods: {
    handleSizeChange(pageSize) {
      console.log('修改当前显示数量:', pageSize)
      this.pageSize = pageSize
      this.fetchList({ pageNum: 1, pageSize: this.pageSize })
    },
    handleCurrentChange(pageNum) {
      console.log('修改当前页码:', pageNum)
      this.pageNum = pageNum
      this.fetchList({ pageNum: this.pageNum, pageSize: this.pageSize })
    },
    handleNodeClick() {

    },
    fetchList(params)/* 查询函数*/ {
      console.log('前端发送请求:', params)
      dataApi(params)
        .then(resp => {
          const { pageNum, pageSize, total, rows } = resp.data
          // 将接收到的来自于服务器的数据保存到data属性中
          this.pageNum = pageNum || this.pageNum
          this.pageSize = pageSize || this.pageSize
          this.total = total || this.total
          this.list = rows || this.list
        }).catch(error => {
          console.log('执行异步请求发生错误', error)
        })
    },
    dictTypeClick(e){
      console.log(e)
    },
    onQuery()/* 条件查询执行*/ {
      // ... 对象扩展符， 将this.formInline对象中的属性复制到当前params对象中
      const params = { pageNum: 1, pageSize: this.pageSize, ...this.formInline }
      console.log('条件查询', this.formInline)
      // 点击查询按钮
      this.fetchList(params)
    },
    tableSelect(x) {
      this.itemBatchData = x
    },

    /* 提交编辑的表单 新增&修改 */
    onSubmitAdd() {
      // 点击立即创建按钮，触发表单提交
      // 在提交表单之前需要校验表单是否通过验证
      this.$refs['fromView'].validate(valid => { // valid是一个buer值
        if (valid) {
          this.fromView.isUserFormLoadding = true
          console.log('提交表单', this.fromView)
          if (this.buttonText.editSubmit === '确认修改') {
            editApi(this.fromView).then(resp => {
              // console.log(resp)  // {code:20000, message:''}
              this.messageFun(1, (resp.message || '修改成功！'))
              // 更新数据
              this.fetchList()
              // 隐藏对话框
              this.dialogVisible = false
              // 重置验证
              this.resetUserForm()
            })
          }
          if (this.buttonText.editSubmit === '立即创建') {
            addApi(this.fromView).then(resp => {
              // console.log(resp)  // {code:20000, message:''}
              this.messageFun(1, (resp.message || '新增成功！'))

              // 更新数据
              this.fetchList()
              // 隐藏对话框
              this.dialogVisible = false
              // 重置验证
              this.resetUserForm()
            })
          }
        }
      })
    },
    handleAdd() /* 弹出对话框*/{
      this.dialogVisible = true
    },
    resetUserForm()/*重置表单校验规则*/{
      this.$refs['fromView'].resetFields()
      this.dialogFormVisible = false
      // 清空用户输入的信息
      this.fromView = {
        type:1,/*请求类型-新增/修改/删除/批量删除*/
          id:undefined, /*字典主键*/
          dictName:undefined, /*字典名称*/
          dictType:undefined, /*字典类型*/
          status:undefined, /*状态*/
          createBy:undefined, /*创建者*/
          createTime:undefined, /*创建时间*/
          updateBy:undefined, /*更新者*/
          updateTime:undefined, /*更新时间*/
          remark:undefined, /*备注*/

        isFormLoadding: false/*记录加载中*/
      }
    },
    closeUserDialog()/*隐藏对话框*/ {
      // 隐藏对话框
      this.dialogFormVisible = false
      // 重置表单
      this.resetUserForm()
    },
    dialogClose()/*关闭当前对话框*/{
      this.dialogVisible = false
      this.resetUserForm()/*重置表单*/
    },
    deleteItem(index,scope,row){
     console.log("正在执行删除:")
     function activeFun(v)/*积极事件*/{

    v.deleteByIdApi(scope[v.primaryKey]).then(resp => {
      v.$message({ type: 'success', message: '删除成功!' })
      // 更新数据
      v.fetchList()
    })


        /* 获取主键*/
        // doPost({type:2,key:scope.userId}).then(resp => {
        //   // console.log(resp)  // {code:20000, message:''}
        //   v.messageFun(1,(resp.message ||"删除成功！"))
        //   v.fetchList();/*更新数据*/
        // })
      }
      function negativeFun()/* 消极事件*/ {
        console.log(555)
      }

      this.messageBox('提示', '此操作将永久删除数据, 是否继续?', 2, '确定', activeFun, '取消', negativeFun)
    },
    editItem(row) {
      this.dialogVisible = true
      this.buttonText.editSubmit = '确认修改'
      Array.from(Object.keys(this.fromView)).map(v => {
        this.fromView[v] = row[v]
      })
      // this.fromView['dept_id'] = row['dept'].deptId
      // this.fromView['type'] = 1
      console.log('正在编辑:', this.fromView)
    },
    /* 确认消息*/messageBox(title, info, messagetype, button1, function1, button2, function2) {
      if (messagetype === 1) { this.infoBoxType = 'success' }
      if (messagetype === 2) { this.infoBoxType = 'warning' }
      if (messagetype === 3) { this.infoBoxType = 'error' }

      console.log(this.infoBoxType)
      this.$confirm(info, title, {
        confirmButtonText: button1,
        cancelButtonText: button2,
        type: this.infoBoxType
      }).then(() => {
        function1(this)
      }).catch(() => {
        function2(this)
      })
    },
    /* 普通消息*/messageFun(type, info) {
      const infoType = 'info'
      if (type === 1) { this.infoType = 'success' }
      if (type === 2) { this.infoType = 'warning' }
      if (type === 3) { this.infoType = 'error' }
      this.$message({
        type: this.infoType,
        duration: 2 * 1000,
        showClose: true,
        message: info
      })
    },
    /* 显示对话框*/showDialog(type) {
      if (type == 1/* 新增*/) {
        this.buttonText.editSubmit = '立即创建'
        this.dialogVisible = true
      }
    },
    /* table批量删除*/itemBatch_DEL() {
      function activeFun(v){
        const arr = Array.from(v.itemBatchData).map(q => {
          return q[v.primaryKey]
        })
        v.deleteByIdApi(arr).then(resp => {
          v.messageFun(1, (resp.message || '删除成功！'))
          v.fetchList()/* 更新数据*/
        })
      }
      function negativeFun(){}
      this.messageBox('提示', '此操作将永久删除数据, 是否继续?', 2, '确定', activeFun, '取消', negativeFun)
    },
    dateFormat(row, column) {
      // console.log(row, column, cellValue, index)
      const daterc = row
      if (daterc != null) {
        var date = new Date(daterc)
        var year = date.getFullYear()
        /* 在日期格式中，月份是从0开始，11结束，因此要加0
                 * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
                 * */
        var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
        var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
        var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
        var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        // 拼接

        return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
      }
    }
  }
}


export default mixin;
